﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Globalization;

namespace AAA.Base.Util.Cryptography
{
    public class DES
    {
        public static string GenerateKey()
        {
            DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create();
            return ASCIIEncoding.ASCII.GetString(desCrypto.Key);
        }

        // 加密字符串
        public static string EncryptString(string sInputString, string sKey, Encoding encoding)
        {            
            byte [] data = encoding.GetBytes(sInputString);
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            ICryptoTransform desencrypt = DES.CreateEncryptor();
            byte [] result = desencrypt.TransformFinalBlock(data, 0, data.Length);
            return BitConverter.ToString(result);
        }

        // 解密字符串
        public static string DecryptString(string sInputString, string sKey, Encoding encoding)
        {
            string [] sInput = sInputString.Split("-".ToCharArray());
            byte [] data = new byte[sInput.Length];
            for(int i = 0; i < sInput.Length; i++)
                data[i] = byte.Parse(sInput[i], NumberStyles.HexNumber);
    
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            ICryptoTransform desencrypt = DES.CreateDecryptor();
            byte [] result = desencrypt.TransformFinalBlock(data, 0, data.Length);
            return encoding.GetString(result);
        }

        // 測試加/解密
        public static void Test()
        {
            string key = DES.GenerateKey();
            string s0 = "加密測試 - AAA";
            string s1 = DES.EncryptString(s0, key, Encoding.Default);
            string s2 = DES.DecryptString(s1, key, Encoding.Default);
            Console.WriteLine("原串: [{0}]", s0);
            Console.WriteLine("加密: [{0}]", s1);
            Console.WriteLine("解密: [{0}]", s2);

        }
    }
   
}
